package com.atguigu.ucenter.member.service.impl;

import com.atguigu.utils.JwtUtils;
import com.atguigu.serviceBash.GlobalException;
import com.atguigu.ucenter.member.entity.Member;
import com.atguigu.ucenter.member.entity.vo.MemberQuery;
import com.atguigu.ucenter.member.mapper.MemberMapper;
import com.atguigu.ucenter.member.service.MemberService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;

/**
 * <p>
 * 会员表 服务实现类
 * </p>
 *
 * @author admin
 * @since 2020-07-12
 */
@Service
public class MemberServiceImpl extends ServiceImpl<MemberMapper, Member> implements MemberService {

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public String login(String mobile, String password) {
        if (StringUtils.isEmpty(mobile) || StringUtils.isEmpty(password)) {
            throw new GlobalException("登录失败!", 20001);
        }
        //md5加密后 进行比对
        password = DigestUtils.md5Hex(password);
        QueryWrapper<Member> wrapper = new QueryWrapper<>();
        wrapper.eq("mobile", mobile);
        wrapper.eq("password", password);
        Member member = baseMapper.selectOne(wrapper);
        if (member == null) {
            throw new GlobalException("手机号或密码错误!", 20001);
        }
        return JwtUtils.getJwtToken(member.getId(), member.getNickname());
    }

    @Override
    public boolean register(MemberQuery memberQuery) {
        //  验证码 手机号 密码 昵称都不可为空
        if (StringUtils.isEmpty(memberQuery.getMobile())) {
            throw new GlobalException("手机号不能为空!", 20001);
        }
        if (StringUtils.isEmpty(memberQuery.getPassword())) {
            throw new GlobalException("密码不能为空!", 20001);
        }
        if (StringUtils.isEmpty(memberQuery.getNickname())) {
            throw new GlobalException("昵称不能为空!", 20001);
        }
        if (StringUtils.isEmpty(memberQuery.getCode())) {
            throw new GlobalException("验证码不能为空!", 20001);
        }
        //  查询手机号是否已经存在 如果存在 不进行注册
        QueryWrapper<Member> wrapper = new QueryWrapper<>();
        wrapper.eq("mobile", memberQuery.getMobile());
        Integer count = baseMapper.selectCount(wrapper);
        wrapper = null;
        if (count > 0) {
            throw new GlobalException("此手机号已注册!", 20001);
        }
        //  查询redis中的验证码是否为空或已失效
        ValueOperations<String, String> value = redisTemplate.opsForValue();
        String userCode = memberQuery.getCode();
        String redisCode = value.get(memberQuery.getMobile());
        if (redisCode == null || "".equals(redisCode)) {
            throw new GlobalException("验证码不存在或已失效!", 20001);
        }
        if (!userCode.equals(redisCode)) {
            throw new GlobalException("验证码错误!", 20001);
        }
        // 上述条件通过 进入注册
        Member member = new Member();
        member.setMobile(memberQuery.getMobile());
        member.setNickname(memberQuery.getNickname());
        //  默认头像
        member.setAvatar("http://thirdwx.qlogo.cn/mmopen/vi_32/DYAIOgq83eoj0hHXhgJNOTSOFsS4uZs8x1ConecaVOB8eIl115xmJZcT4oCicvia7wMEufibKtTLqiaJeanU2Lpg3w/132");
        //  密码进行md5加密存储
        member.setPassword(DigestUtils.md5Hex(memberQuery.getPassword()));
        try {
            int insert = baseMapper.insert(member);
            if (insert > 0) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }

    /**
     * 登录成功后 根据id查询用户信息
     *
     * @param id id
     * @return Member
     */
    @Override
    public Member getMemberByToken(String id) {
        QueryWrapper<Member> wrapper = new QueryWrapper<>();
        wrapper.eq("id", id);
        Member member = baseMapper.selectOne(wrapper);
        wrapper = null;
        return member;
    }

    @Override
    public String wxLogin(HashMap<String, String> userInfo) {
        String openid = userInfo.get("openid");
        QueryWrapper<Member> wrapper = new QueryWrapper<>();
        wrapper.eq("openid", openid);
        Member member = baseMapper.selectOne(wrapper);
        //根据openid查询 是否存在该用户 如果已存在 返回token令牌
        if (member != null) {
            return JwtUtils.getJwtToken(member.getId(), member.getNickname());
        }
        //openid不存在 进行注册后返回token令牌
        String nickname = userInfo.get("nickname");
        String headimgurl = userInfo.get("headimgurl");
        try {
            nickname = new String(nickname.getBytes("ISO8859-1"), StandardCharsets.UTF_8.name());
            headimgurl = new String(headimgurl.getBytes("ISO8859-1"), StandardCharsets.UTF_8.name());
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        member = new Member();
        member.setOpenid(openid);
        member.setNickname(nickname);
        member.setAvatar(headimgurl);

        int insert = baseMapper.insert(member);
        if (insert > 0) {
            return JwtUtils.getJwtToken(member.getId(), member.getNickname());
        }
        throw new GlobalException("未知错误!", 20001);

    }

    @Override
    public int getRegisterCount(String date) {
        int count = 0;
        try {
            DateFormat.getDateInstance();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String dat = sdf.format(sdf.parse(date));
            sdf = null;
            count = baseMapper.getCount(dat);

        } catch (Exception e) {
            e.printStackTrace();
            throw new GlobalException("日期格式有误", 20001);
        }
        return count;
    }


}
